package com.vegetable.modules.service.wx;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.common.utils.HttpUtil;
import com.vegetable.modules.entity.sys.SysLogEntity;
import com.vegetable.modules.entity.wx.WxDepartment;
import com.vegetable.modules.mapper.sys.SysLogDao;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业微信部门同步服务
 * 用于从企业微信拉取通讯录部门结构
 *
 * @author Qoder
 */
@Slf4j
@Service
public class WxCpDepartmentSyncService {

    @Value("${wechat.cp.corpId}")
    private String corpId;
    
    @Value("${wechat.cp.appConfig.secret}")
    private String corpSecret;
    
    @Autowired
    private WxCpService wxCpService;
    
    @Autowired
    private SysLogDao sysLogDao;
    
    @Autowired
    private WxDepartmentService wxDepartmentService;

    /**
     * 获取企业微信access_token
     * 
     * @return access_token
     * @throws Exception 获取失败时抛出异常
     */
    private String getAccessToken() throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret;
        String res = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String accessToken = null;
        if (CollectionUtil.isNotEmpty(jsonObject)) {
            accessToken = jsonObject.getString("access_token");
        }
        if (accessToken == null || accessToken.isEmpty()) {
            throw new Exception("ACCESS_TOKEN 获取失败");
        }
        return accessToken;
    }

    /**
     * 获取企业微信部门列表
     * 
     * @return 部门列表
     * @throws Exception 获取失败时抛出异常
     */
    public List<WxCpDepart> getDepartmentList() throws Exception {
        try {
            // 使用企业微信SDK获取部门列表
            return wxCpService.getDepartmentService().list(null);
        } catch (WxErrorException e) {
            log.error("获取企业微信部门列表失败", e);
            throw new Exception("获取企业微信部门列表失败: " + e.getMessage());
        }
    }

    /**
     * 同步企业微信部门结构
     * 
     * @throws Exception 同步失败时抛出异常
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncDepartmentStructure() throws Exception {
        log.info("开始同步企业微信部门结构");
        
        try {
            // 1. 获取所有部门
            List<WxCpDepart> wxDepartments = getDepartmentList();
            log.info("获取到 {} 个部门", wxDepartments.size());
            
            // 2. 转换并保存部门信息到数据库
            List<WxDepartment> departments = new ArrayList<>();
            for (WxCpDepart wxDepart : wxDepartments) {
                WxDepartment department = new WxDepartment();
                department.setId(wxDepart.getId());
                department.setName(wxDepart.getName());
                department.setParentId(wxDepart.getParentId());
                department.setOrderNum(wxDepart.getOrder());
                departments.add(department);
            }
            
            // 批量保存部门信息
            wxDepartmentService.saveDepartments(departments);
            log.info("保存了 {} 个部门信息到数据库", departments.size());
            
            log.info("企业微信部门结构同步完成");
        } catch (Exception e) {
            log.error("同步企业微信部门结构失败", e);
            throw e;
        }
    }
    
    /**
     * 从数据库获取所有部门信息（不实时从企业微信获取）
     * 
     * @return 部门列表
     */
    public List<WxDepartment> getLocalDepartments() {
        log.info("开始从数据库获取所有部门信息");
        
        // 直接从数据库查询所有部门信息
        List<WxDepartment> departments = wxDepartmentService.list();
        
        log.info("从数据库获取到 {} 个部门", departments.size());
        return departments;
    }
}